package com.lyeducation.util.mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import java.util.Properties;

@Configuration
public class MailConfig {
  @Autowired MailSender mailSender;

  @Bean(name = "JavaMailSender")
  public JavaMailSender getSender() {
    JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
    javaMailSender.setUsername(mailSender.getForm());
    javaMailSender.setPassword(mailSender.getFormPassword());
    javaMailSender.setHost(mailSender.getHost());
    javaMailSender.setPort(mailSender.getPort());
    javaMailSender.setDefaultEncoding("UTF-8");
    Properties props = new Properties();
    props.setProperty("mail.smtp.host", mailSender.getHost());
    props.setProperty("mail.smtp.auth", mailSender.getAuth());
    javax.mail.Session session =
        javax.mail.Session.getDefaultInstance(
            props,
            new Authenticator() {
              @Override
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    mailSender.getForm(), mailSender.getFormPassword());
              }
            });
    javaMailSender.setSession(session);
    return javaMailSender;
  }
}
